<?php
namespace Manage\Model;
use Think\Model;
class AttributeGroupModel extends Model{
	private $Model;
	function _initialize(){
		$this->Model=M('AttributeGroupDescription');
	}
	public function operAttributeGroup($data,$attribute_group_id=0){
		$agdata	=	$this->create($data);
		if($attribute_group_id){
			$this->where(array('attribute_group_id'=>$attribute_group_id))->save($agdata);
		}else{
			$attribute_group_id=$this->add($agdata);
		}
		$map['attribute_group_id']=$attribute_group_id;
		$this->Model->where($map)->delete();
		foreach ($data['attribute_group_description'] as $language_id => $attribute_group_description) {
			$attribute_group_description['language_id']=$language_id;
			$attribute_group_description['attribute_group_id']=$attribute_group_id;
			$this->Model->add($attribute_group_description);
		}
	}
	public function getById($attribute_group_id){
		$map['attribute_group_id']=$attribute_group_id;
		$return=$this->where($map)->find();
		$ag=$this->Model->where($map)->select();
		foreach ($ag as $v) {
			$return['attribute_group_description'][$v['language_id']]=$v;
		}
		return $return;
	}
	public function getAttrGroups($data=array()){
		$page=array(
			'start'		=>	$data['start']?$data['start']:0,
			'limit'		=>	$data['limit']?$data['limit']:C('CONFIG_LIMIT_MANAGE')
			);
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		$order='sort_order '. ($data['order']?$data['order']:'ASC');
		$order .= ',' . C('DB_PREFIX') . 'attribute_group.attribute_group_id DESC';
		$return=$this->join('LEFT JOIN __ATTRIBUTE_GROUP_DESCRIPTION__ ON __ATTRIBUTE_GROUP__.attribute_group_id=__ATTRIBUTE_GROUP_DESCRIPTION__.attribute_group_id')->where($map)->order($order)->limit($page['start'],$page['limit'])->select();
		return $return;
	}
	public function getAll(){
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		$order='sort_order ASC';
		$order .= ',' . C('DB_PREFIX') . 'attribute_group.attribute_group_id DESC';
		$return=$this->join('LEFT JOIN __ATTRIBUTE_GROUP_DESCRIPTION__ ON __ATTRIBUTE_GROUP__.attribute_group_id=__ATTRIBUTE_GROUP_DESCRIPTION__.attribute_group_id')->where($map)->order($order)->select();
		return $return;
	}
	public function getCount(){
		return $this->count();
	}
	public function del($attribute_group_id){
		$map['attribute_group_id']=$attribute_group_id;
		$attrs=M('Attribute')->where($map)->select();
		if($attrs){
			$attrs=array_column($attrs,'attribute_id');
			$dmap['attribute_id']=array('in',$attrs);
			$PAModel = M('ProductAttribute');
			//删除商品属性表中与之相关的记录
			$PAModel->where($dmap)->delete();
			//删除此分组下所有的属性
			M('AttributeDescription')->where($dmap)->delete();
			M('Attribute')->where($map)->delete();
		}
		//删除自身
		$this->Model->where($map)->delete();
		return $this->where($map)->delete();
	}
}